<template>
	<view class="orders-page">
		<scroll-view scroll-x class="tabs" :show-scrollbar="false">
			<view v-for="t in tabs" :key="t.key" class="tab" :class="{active: current===t.key}" @click="switchTab(t.key)">{{t.label}}</view>
		</scroll-view>

		<view v-if="current!=='refund'" class="list">
			<view class="order" v-for="o in orders" :key="o.id">
				<view class="order-hd">
					<text class="shop">{{ o.merchantName || '海D捞旗舰店' }}</text>
					<text class="st">{{ mapStatus(o.status) }}</text>
				</view>
				<view class="order-bd">
					<view class="line" v-for="it in o.items||[]" :key="it.id">
						<image class="pic" :src="getImageUrl(it.coverImage)" mode="aspectFill" />
						<view class="meta">
							<text class="title">{{it.title}}</text>
							<text class="qty">数量：x{{it.quantity}}</text>
						</view>
						<text class="price">¥{{it.price}}</text>
					</view>
				</view>
				<view class="order-ft">
					<text class="order-no">订单号：{{o.id}}</text>
					<view class="amount-info">
						<view v-if="o.originalAmount && Number(o.originalAmount) !== Number(o.totalAmount)" class="amount-row">
							<text class="label">原价：</text>
							<text class="original-amount">¥{{Number(o.originalAmount).toFixed(2)}}</text>
						</view>
						<view v-if="o.discountAmount && Number(o.discountAmount) > 0" class="amount-row discount-row">
							<text class="label">优惠：</text>
							<text class="discount-amount">-¥{{Number(o.discountAmount).toFixed(2)}}</text>
						</view>
						<view class="amount-row total-row">
							<text class="label">实付：</text>
							<text class="sum">¥{{Number(o.totalAmount).toFixed(2)}}</text>
						</view>
					</view>
				</view>
				<view class="order-ops">
					<button v-if="o.status==='CREATED'" class="op primary" @click="pay(o)">去支付</button>
					<button v-if="o.status==='CREATED'" class="op" @click="applyRefund(o)">申请退款</button>
					<button v-if="o.status==='PAID'" class="op" @click="applyRefund(o)">申请退款</button>
					<button v-if="o.status==='SHIPPED'" class="op" @click="applyRefund(o)">申请退款</button>
					<button v-if="o.status==='SHIPPED'" class="op primary" @click="confirmReceive(o)">确认收货</button>
					<button v-if="o.status==='COMPLETED' && hasPendingComment(o)" class="op" @click="comment(o)">去评价</button>
				</view>
			</view>
		</view>

		<view v-else class="list">
			<view class="refund-card" v-for="r in refunds" :key="r.id">
				<view class="refund-hd">
					<text class="shop">{{ r.order?.merchantName || '海D捞旗舰店' }}</text>
					<text class="st">{{ mapRefundStatus(r.status) }}</text>
				</view>
				<view class="refund-body">
					<image class="pic" :src="getImageUrl(r.item?.coverImage)" mode="aspectFill" />
					<view class="meta">
						<text class="title">{{ r.item?.title || '商品' }}</text>
						<text class="qty">数量：x{{ r.item?.quantity || '-' }}</text>
					</view>
					<text class="price">¥{{ r.item?.price || '-' }}</text>
				</view>
				<view class="refund-reason">申请原因：{{ r.reason || '无' }}</view>
				<view class="refund-ft">
					<text class="time">{{ formatTime(r.createdAt) }}</text>
					<view class="ops">
						<button class="op" @click="viewRefund(r)">售后详情</button>
						<button class="op danger" @click="deleteRefund(r)">删除</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { api } from '../../utils/request.js'
import { BASE_URL } from '../../utils/server.js'

export default {
	data(){
		return {
			current: 'all',
			tabs: [
				{ key: 'all', label: '全部' },
				{ key: 'pendingPay', label: '待付款' },
				{ key: 'pendingShip', label: '待发货' },
				{ key: 'pendingReceive', label: '待收货' },
				{ key: 'pendingComment', label: '待评价' },
				{ key: 'refund', label: '退款/售后' }
			],
			orders: [],
			refunds: []
		}
	},
	onLoad(q){
		if(q && q.tab){ this.current = q.tab; }
		this.fetch();
	},
	methods:{
		switchTab(key){ this.current = key; this.fetch(); },
		mapStatus(s){ const m={CREATED:'待付款',PAID:'待发货',SHIPPED:'待收货',COMPLETED:'已完成',CANCELED:'已取消'}; return m[s]||s; },
		async fetch(){
			if(this.current==='refund'){
				const r = await api.getRefunds();
				if(r.code===0){ this.refunds = r.data||[]; } else { this.refunds=[]; }
				return;
			}
			const statusMap={ pendingPay:'CREATED', pendingShip:'PAID', pendingReceive:'SHIPPED', pendingComment:'COMPLETED' };
			const params={ pageNum:1, pageSize:20 };
			if(statusMap[this.current]) params.status=statusMap[this.current];
			const res = await api.getOrders(params);
			if(res.code===0){
				let list = res.data.records || res.data || [];
				if(this.current==='pendingComment'){
					list = list.filter(o => (o.items||[]).some(it=>!it.reviewed));
				}
				this.orders = list;
			}else{
				this.orders = [];
			}
		},
		pay(o){
			const payload = encodeURIComponent(JSON.stringify({
				id: o.id,
				merchantName: o.merchantName,
				totalAmount: o.totalAmount,
				originalAmount: o.originalAmount || o.totalAmount,
				discountAmount: o.discountAmount || 0,
				items: (o.items || []).map(it => ({
					productId: it.productId,
					title: it.title,
					price: it.price,
					quantity: it.quantity,
					coverImage: it.coverImage
				}))
			}));
			uni.navigateTo({ url: `/pages/order/confirm?type=order&order=${payload}` });
		},
		applyRefund(o){
			if(!o || !o.items || o.items.length===0){
				uni.showToast({ icon:'none', title:'暂无可申请商品' });
				return;
			}
			const payload = {
				order: { 
					id: o.id, 
					merchantName: o.merchantName || '海D捞旗舰店',
					totalAmount: o.totalAmount,
					originalAmount: o.originalAmount || o.totalAmount,
					discountAmount: o.discountAmount || 0
				},
				item: o.items[0]
			};
			uni.navigateTo({ url: `/pages/refund/detail?order=${encodeURIComponent(JSON.stringify(payload))}` });
		},
		async confirmReceive(o){
			try{
				const r = await api.confirmOrder(o.id);
				if(r.code===0){ uni.showToast({ title:'已完成收货' }); this.fetch(); }
				else { uni.showToast({ icon:'none', title:r.message||'操作失败' }); }
			} catch { uni.showToast({ icon:'none', title:'请求失败' }); }
		},
		hasPendingComment(o){ return (o?.items||[]).some(it=>!it.reviewed); },
		comment(o){
			const pending = (o?.items||[]).find(it=>!it.reviewed);
			if(!pending){ uni.showToast({icon:'none', title:'暂无可评价商品'}); return; }
			const payload = encodeURIComponent(JSON.stringify({ orderId:o.id, item:pending }));
			uni.navigateTo({ url: `/pages/review/create?data=${payload}` });
		},
		refreshOrders(){ this.fetch(); },
		mapRefundStatus(s){ const m={PENDING:'处理中',APPROVED:'已通过',REJECTED:'已拒绝',COMPLETED:'已完成'}; return m[s]||s; },
		formatTime(t){ if(!t) return ''; try{ return t.replace('T',' ').substring(0,19); }catch{ return t; } },
		viewRefund(r){ uni.navigateTo({ url: `/pages/refund/detail?refundId=${r.id}` }); },
		async deleteRefund(r){
			try{
				const res = await api.deleteRefund(r.id);
				if(res.code===0){ uni.showToast({ title:'已删除' }); this.fetch(); }
				else{ uni.showToast({ icon:'none', title: res.message || '删除失败' }); }
			}catch{ uni.showToast({ icon:'none', title:'删除失败' }); }
		},
		getImageUrl(url) {
			if (!url) return '/static/logo.png';
			if (url.startsWith('http')) return url;
			return BASE_URL + url;
		}
	}
}
</script>

<style>
.orders-page{ padding: 16rpx; }
.tabs{ white-space: nowrap; display: flex; gap: 12rpx; margin-bottom: 16rpx; }
.tab{ display:inline-block; padding: 12rpx 20rpx; background:#f6f7f9; border-radius: 999rpx; font-size: 26rpx; color:#666; }
.tab.active{ background:#fff; color:#ff4d4f; box-shadow:0 6rpx 18rpx rgba(0,0,0,.06); }
.list{ display:flex; flex-direction: column; gap: 16rpx; }
.order, .refund-card{ background:#fff; border-radius: 16rpx; box-shadow:0 6rpx 20rpx rgba(0,0,0,.05); overflow:hidden; }
.order-hd, .refund-hd{ display:flex; justify-content: space-between; padding: 20rpx; border-bottom: 2rpx solid #f4f5f6; }
.shop{ font-weight: 600; color:#333; }
.no{ color:#333; }
.st{ color:#ff7a45; }
.order-bd{ padding: 8rpx 20rpx; }
.line{ display:flex; align-items:center; padding: 16rpx 0; border-bottom: 2rpx solid #f6f6f7; }
.line:last-child{ border-bottom: 0; }
.pic{ width: 120rpx; height: 120rpx; background:#fafafa; border-radius: 12rpx; margin-right: 16rpx; }
.meta{ flex:1; }
.title{ display:block; color:#333; font-size: 28rpx; }
.qty{ color:#999; font-size: 24rpx; }
.price{ color:#FF4D4F; font-weight: 600; }
.order-ft{ display:flex; flex-direction: column; gap: 8rpx; padding: 16rpx 20rpx; }
.order-no{ color:#999; font-size: 24rpx; }
.amount-info{ display:flex; flex-direction: column; gap: 6rpx; align-items: flex-end; }
.amount-row{ display:flex; align-items:center; gap: 8rpx; font-size: 26rpx; }
.amount-row .label{ color:#666; }
.original-amount{ color:#999; text-decoration: line-through; }
.discount-row .label{ color:#ff7a45; }
.discount-amount{ color:#ff7a45; }
.total-row .label{ color:#333; font-weight: 600; }
.sum{ color:#ff4d4f; font-weight: 700; font-size: 28rpx; }
.order-ops{ display:flex; gap: 12rpx; justify-content: flex-end; padding: 0 20rpx 16rpx; }
.op{ padding: 10rpx 22rpx; font-size: 26rpx; border-radius: 999rpx; border:2rpx solid #ddd; background:#fff; color:#333; }
.op.primary{ border-color:#ff7a45; color:#ff7a45; }
.refund-body{ display:flex; align-items:center; padding: 16rpx 20rpx; gap: 16rpx; }
.refund-reason{ padding: 0 20rpx 12rpx; color:#666; font-size: 26rpx; }
.refund-ft{ display:flex; align-items:center; justify-content: space-between; padding: 0 20rpx 18rpx; }
.time{ color:#999; font-size: 24rpx; }
.ops{ display:flex; gap: 12rpx; }
.op.danger{ border-color:#f56c6c; color:#f56c6c; }
.ops .op{ min-width: 160rpx; text-align:center; }
</style>

